package com.gg.common.helper;

import com.alibaba.excel.util.StringUtils;
import io.jsonwebtoken.*;

import java.util.Date;

/**
 * Author：  chenjunjia
 * Date：    2022/4/19 0:12
 * WeChat：  China_JoJo_
 */
public class JWTHelper {

    //token过期时间设置
    private static long tokenExpiration = 24*60*60*1000;
    //签名秘钥，根据这个来做加密
    private static String tokenSignKey = "123456";

    //根据用户ID、用户名，生成token
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("REGISTRATION-USER")//分类
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))//设置过期时间：采用当前时间毫秒数+限度时间毫秒数
                .claim("userId", userId)//采用 key-value
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)//签名哈希，根据这个做编码处理
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    //根据token得到用户ID
    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)) return null;
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");//根据key拿到value
        return userId.longValue();
    }
    //根据token得到用户名
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");//根据key拿到value
    }
    public static void main(String[] args) {
        String token = JWTHelper.createToken(122L, "小明");
        System.out.println(token);
        //token由三部分组成：头，主体，签名哈希
//        String test = "eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJSCnJ19wwOCXIM8fT30w0Ndg1S0lFKrShQsjI0MzU0MDMxMTTTUSotTi3yTAGKWULYfom5qUC9Lxo2P9kx5-XMDqVaAF4DYTFPAAAA.UJ-k9r7dmFg1qpPds3IT4TFxsHcFqyDUTspWnB7bKoEp5SchNpJh1CEkpD78AUgPGnyZie0SrajqF2jh36miJg";
        System.out.println("用户ID："+JWTHelper.getUserId(token));
        System.out.println("用户名："+JWTHelper.getUserName(token));
    }
}
